var ONLINE_BASEURL = "http://www.mysee.cc:18308";
var event_id = "35119c9c9b54486f9538152fc77178d1";
var downpage_url = "down_page.html";
var $progressBar = null;
function updateImages(imgurl) {
    var width = 0;
    var height = 0;
    var url = null;
    if (imgurl == null || imgurl.length <= 0) {
        $("#event_pic").css("display", "none");
    } else {
        $("#event_pic").css("display", "block"); 
    }
    var imgs = $(".event_pic img");
    for (var i=0; i < imgs.length; i++) {
        try {
            width = parseInt($(imgs[i]).width());
            height = parseInt($(imgs[i]).height());
            var newUrl = generateUrlWithWH(imgurl[i], width, height);
            if (newUrl == null || newUrl.trim() == "") {
                $(imgs[i]).css("display", "none");
            } else {
                $(imgs[i]).css("display", "inline");
            }
            $(imgs[i]).attr("src", newUrl);
            $(imgs[i]).attr("srcurl", imgurl[i]);
            $(imgs[i]).attr("index", i+1);
            // console.log("i : " + i + " , newUrl : " + newUrl);
            $(imgs[i]).click(function() {
                urlsrc = $(this).attr("srcurl");
                showPreviewImage(urlsrc, $(this).attr("index"));
            });
        } catch(e) {
            console.log(e);
        }
    }
    $("#preview_img,#preview_div").click(function () {
        $("#preview_div").fadeOut();
    });
    $("#images_div").css("display", "block");
}

/**
* 显示全屏图片
*/
function showPreviewImage(imgurl, index) {
    $("#preview_div").height($(window).height());
    $("#preview_div").fadeIn();
    $("#preview_img_loading").show();
    $("#preview_img").hide();
    var url2 = generateUrlWithWH(imgurl, $("#preview_div").width(), $("#preview_div").height());
    $("#extra_title").text("第" + index + "张");
    $("#extra_title").hide();
    $("#preview_img").attr("src",url2);
}

function generateUrlWithWH(url, w, h) {
    try {
        var srcUrl = url;
        var index = srcUrl.lastIndexOf(".");
        var name = srcUrl.substring(0, index);
        var ext =  srcUrl.substring(index, srcUrl.length);
        var newUrl = name + "_" + 2*w + "x" + 2*h + ext;
        return newUrl;
    } catch(e) {
    }
    return url;
}
function isWeiXin() {
    var ua = window.navigator.userAgent.toLowerCase();
    // console.log(ua);//mozilla/5.0 (iphone; cpu iphone os 9_1 like mac os x) applewebkit/601.1.46 (khtml, like gecko)version/9.0 mobile/13b143 safari/601.1
    if (ua.match(/MicroMessenger/i) == 'micromessenger') {
        return true;
    } else {
        return false;
    }
}

function hideTitleAreaInWx() {
    if (isWeiXin()) {
        $(".page_top").hide();
        $(".event_body").css("top","0em");
    } else {
        $(".page_top").show();
        $(".event_body").css("top","56px");
    }
}

function configUrl(url, map) {
    if (map == null) {
        map = {};
    }
    var date = Date.now();
    var query = [];
    for (var tmp in map) {
        query.push(tmp + "=" + map[tmp])
    }
    query.push("rnd=" + date);
    var orgStr = query.join('&');
    md5str = hex_md5(orgStr + "mysee.cc!$!&!&!&!$");
    query.push("sign=" + md5str);
    url += "?";
    url += query.join('&');
    return url;
}

function showDetail() {
    var url = ONLINE_BASEURL + "/mse-web/mysee/search/searchRescueById.do";
    url = configUrl(url);
    var data = '{"id":"' + event_id + '"}';
    console.log(data);
    $.support.cors = true;
    $.ajax({
        url : url,
        data : data,
        type: "POST",
        dataType:"json",
        contentType:"application/json",
        success: function(data){
            updateContentView(data);
        },
        error: function(e) {
            updateContentView(null);
        }
    });
}
var isJson = function(obj){
    var isjson = typeof(obj) == "object" && Object.prototype.toString.call(obj).toLowerCase() == "[object object]" && !obj.length;
    return isjson;
}

function addPreviewFunctionForImages() {
    $("#event_content img").each(function(){
        $(this).click(function() {
            showPreviewImage($(this).attr("src"), 0);
        });
    });
}

function callback(data) {
    // console.log(JSON.stringify(data));
    updateContentView(data);
}
function formatDate(time) {
    try {
        var date = new Date();
        date.setTime(time);
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        if (month < 10) month = "0" + month;
        var day = date.getDate();
        if (day < 10) day = "0" + day;
        var hour = date.getHours();
        if (hour < 10) hour = "0" + hour;
        var minute = date.getMinutes();
        if (minute < 10) minute = "0" + minute;
        return year + "-" + month + "-" + day + " " + hour + ":" + minute;
    }catch(e) {
    }
    return "";
}
function isEmptyObject(e) {  
    var t;  
    for (t in e)  
        return !1;  
    return !0  
}

function showErrorPage() {
    console.log("请求数据异常");
    $("<div id='error_page'></div>").css({"width":"100%", "height":"100%", "text-align":"center", "position":"absolute", "margin":"0", "padding":"0"}).appendTo($(document.body));
    $("<p>请求数据异常</p>").css({"position":"absolute", "top":"50%", "left":"50%", "transform":"perspective(1200px) translate3d(-50%,-50%,0) scale(1)"}).appendTo($("#error_page"));
    hideProgressBar();
}

function showSuccessPage() {
    $("#container").show();
    hideProgressBar();
}

function updateContentView(data) {
    // console.log(JSON.stringify(data));
    // console.log(typeof data);
    if (data == null || !isJson(data) || data.errorCode != 0 || isEmptyObject(data.data)) {
        showErrorPage();
        return;
    }
    showSuccessPage();
    document.title = "[" + data.data.typeName + "]" + data.data.title;
    $("#event_title").html("<font color=red>[" + data.data.typeName + "]</font>&nbsp;" + data.data.title);
    $("#pubtime").text("发布时间：" + formatDate(data.data.updateTime));
    if (data.data.orgInfo == null) {
        $("#org_div").css("display","none");
    } else {
        $("#org_div").css("display","block");
        $("#org_name").text(data.data.orgInfo.orgName);
        $("#org_slogon").text(data.data.orgInfo.slogan);
        $("#org_icon").attr("src",generateUrlWithWH(data.data.orgInfo.logo, $("#org_icon").width(), $("#org_icon").height()));
    }
    // console.log(data.data.promoter.nickName);
    $("#promoter").text(data.data.promoter != null ? data.data.promoter.nickName : null);
    $("#promoter_sign").text(data.data.promoter != null ? data.data.promoter.signature : null);
    $("#promoter_icon").attr("src",generateUrlWithWH(data.data.promoter != null ? data.data.promoter.photo : null, $("#promoter_icon").width(), $("#promoter_icon").height()));

    $("#aidedperson").text(data.data.aidedperson != null ? data.data.aidedperson.nickName : null);
    $("#aidedperson_sign").text(data.data.aidedperson != null ? data.data.aidedperson.signature : null);
    $("#aidedperson_icon").attr("src",generateUrlWithWH(data.data.aidedperson != null ? data.data.aidedperson.photo : null, $("#aidedperson_icon").width(), $("#aidedperson_icon").height()));

    $("#event_content").html(data.data.content);
    addPreviewFunctionForImages();
    try {
        var images = data.data.imgUrl.split(',');
        updateImages(images);
    } catch(e) {
    }
}
function addQueryParams(url, key, value) {
    try {
        if (url.indexOf("?") > -1) {
            url = url + "&" + key + "=" + value;
        } else {
            url = url + "?" + key + "=" + value;
        }
    } catch(e){
        console.log("e : " + e);
    }
    return url;
}
function getQueryParams(url, key) {
    map = {};
    try {
        var params = url.split("?")[1];
        var keyvalue = params.split("&");
        for (var index = 0; index < keyvalue.length; index++) {
            var tmp = keyvalue[index].split("=");
            try{
                map[tmp[0]] = tmp[1];
            }catch(e){
            }
        }
    } catch(e){
        console.log("e : " + e);
    }
    return map[key];
}
function initOpenApp() {
    $("#opendetail").click(function() {
        if (isWeiXin()) {
            var opening = getQueryParams(window.location.href, "opening");
            console.log("opening : " + opening);
            if (!opening) {
                window.location.href = addQueryParams(window.location.href, "opening", true);
            }
            console.log("window.location.href : " + window.location.href);
        } else {
            openAppByIFrame();
        }
    });
}
function openAppByIFrame() {
    $iframe = $("<iframe></iframe>");
    var query = [];
    query.push("event_id=" + event_id);
    // query.push("event_title=" + $("#event_title").text());
    // query.push("event_type_label=" + $("#event_type").text());
    // query.push("event_time=" + Date.now());
    var url = "mysee://event_detail";
    url = url + "?" + query.join("&");
    $iframe.attr("src", url);
    $iframe.css("display", "none");
    $(document.body).append($iframe);
    var start = Date.now();
    setTimeout(function(){
        $iframe.remove();
        var end = Date.now();
        if (end - start < 500 + 100) {
            window.location.href = "down_page.html";
        }
    }, 500);
}

function showWeixinShadow() {
    $div = $("<div></div>")
    $div.css({"position" : "fixed", "width":"100%", "height":"100%", "background":"rgba(48, 48, 48, 1.0)", "margin":0, "padding":0, "z-index":2000, "top":0});
    $div[0].addEventListener("touchmove", function(e){e.preventDefault();}, false);
    $div[0].addEventListener("scroll", function(e){e.preventDefault();}, false);
    $div[0].addEventListener("mousewheel", function(e){e.preventDefault();}, false);
    $(document.body).append($div);
    $tips = $("<h2><span style='text-align:center;width:32px;height:32px;display:inline-block;border-radius:16px;background:red;'>1</span>&nbsp;请点击右上角功能图标</h2>")
    $tips.css({"color":"white", "line-height":"33px", "margin":"1em"});
    $tips.appendTo($div);
    $tips = $("<h2><span style='text-align:center;width:32px;height:32px;display:inline-block;border-radius:16px;background:red;'>2</span>&nbsp;选择在浏览器中打开</h2>")
    $tips.css({"color":"white", "line-height":"33px", "margin":"1em"});
    $tips.appendTo($div);
    $("title").text("打开浏览器");
}
/*
*使用JS跨域的方案，向服务器请求数据
*测试服务器使用的代码
*/
function fetchData() {
    var script = document.createElement("script");
    // script.src = "data/event_detail.js";
    var url = "http://taugin.oicp.net:8080/index/cgi-bin/event_detail_jsonp.py";
    url = configUrl(url, {"id":event_id});
    // console.log("scripturl : " + url);
    script.src = url;
    script.type = "text/javascript";
    script.id = "id_event_data";
    var head = document.getElementsByTagName("head");
    if(head && head[0]) {
        head[0].appendChild(script);
    }
}

function createProgressBar() {
    $progressBar = $("<div id='progress_bar'><img src='images/big_progress.gif'/></div>");
    $progressBar.css({"width":"100%", "height":"100%", "position":"fixed", "z-index":"2000","background":"rgba(256, 256, 256, 1)", "top":"0", "text-align":"center"});
    $progressBar.children("img").css({"position":"fixed", "top":"50%", "left":"50%","margin":"-24px 0 0 -24px"});
    $progressBar.children("img").width(48).height(48);
}
function showProgressBar() {
    $(document.body).append($progressBar);
}
function hideProgressBar() {
    $("#progress_bar").remove();
}
function init() {
    event_id = getQueryParams(window.location.href, "id");
    var opening = getQueryParams(window.location.href, "opening");
    console.log("opening : " + opening);
    if (opening) {
        if (isWeiXin()) {
            showWeixinShadow();
            return;
        }
    }
    // For Test
    // showWeixinShadow();
    hideTitleAreaInWx();
    initOpenApp();
    if (isOnlineUrl()) {
        showDetail();
    } else {
        fetchData();
    }
    if (opening) { 
        if (!isWeiXin()) {
            openAppByIFrame();
        }
    }
}

function isOnlineUrl() {
    try {
        return window.location.href.startsWith(ONLINE_BASEURL);
    } catch(e) {
    }
    return false;
}

function initPreviewElement() {
    $("#preview_img").on("load", function() {
        $("#preview_img_loading").hide();
        $("#preview_img").show();
    });
    $("#preview_img").on("error", function() {
        $("#preview_img_loading").hide();
        $("#preview_img").show();
    });
    $("#preview_div")[0].addEventListener("touchmove", function(e){e.preventDefault();}, false);
    $("#preview_img")[0].addEventListener("touchmove", function(e){e.preventDefault();}, false);
    $("#preview_div")[0].addEventListener("scroll", function(e){e.preventDefault();}, false);
    $("#preview_img")[0].addEventListener("scroll", function(e){e.preventDefault();}, false);
    $("#preview_div")[0].addEventListener("mousewheel", function(e){e.preventDefault();}, false);
    $("#preview_img")[0].addEventListener("mousewheel", function(e){e.preventDefault();}, false);
}

$(document).ready(function() {
    console.log("ready");
    $("#container").hide();
    createProgressBar();
    showProgressBar();
    init();
    initPreviewElement();
});